import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { VxeGridPropTypes } from 'vxe-table';
import {
  FilterOperate,
  type PageQuery,
  type FilterRule,
  ListSortDirection,
} from './types';

type Column<D = any> = VxeGridPropTypes.Column<D>;

interface PageInfo {
  currentPage: number;
  pageSize: number;
}

type ProxySort = { field: string; order: string };

/**
 * 根据值的类型确定合适的过滤操作符
 * @param value 要过滤的值
 * @returns FilterOperate 过滤操作符
 */
export function getFilterOperateByValue(value: any): FilterOperate {
  if (value === null || value === undefined) {
    return FilterOperate.Equal;
  }

  switch (typeof value) {
    case 'string':
      return FilterOperate.Contains;
    case 'number':
    case 'boolean':
      return FilterOperate.Equal;
    case 'object':
      if (Array.isArray(value)) {
        return FilterOperate.Contains;
      }
      if (value instanceof Date) {
        return FilterOperate.GreaterOrEqual;
      }
      return FilterOperate.Equal;
    default:
      return FilterOperate.Equal;
  }
}

/**
 * 构建分页查询参数
 * @param page 分页信息
 * @param sorts 排序信息
 * @param formValues 表单值
 * @returns PageQuery 查询参数
 */
export function buildPageQuery(
  page: PageInfo,
  sorts: ProxySort | ProxySort[] | null,
  formValues?: Record<string, any>,
): PageQuery {
  const query: PageQuery = {
    pageCondition: {
      pageIndex: page.currentPage,
      pageSize: page.pageSize,
      sortConditions: [],
    },
    filterGroup: { groups: [], rules: [], operate: FilterOperate.And },
  };

  // 处理排序条件
  if (sorts) {
    const sortArray = Array.isArray(sorts)
      ? sorts
      : sorts && Object.keys(sorts).length > 0
        ? [sorts]
        : [];
    query.pageCondition.sortConditions = sortArray.map((item) => ({
      sortField: item.field,
      listSortDirection:
        item.order === 'desc'
          ? ListSortDirection.Descending
          : ListSortDirection.Ascending,
    }));
  }

  // 处理查询条件
  if (formValues) {
    const rules = Object.entries(formValues)
      .filter(
        ([, value]) => value !== undefined && value !== null && value !== '',
      )
      .map(([field, value]) => ({
        field,
        value: String(value),
        operate: getFilterOperateByValue(value),
      })) as FilterRule[];

    if (rules.length > 0) {
      query.filterGroup.rules = rules;
    }
  }

  return query;
}

/**
 * 创建基础表格配置
 * @param pageQueryApi 分页数据查询API函数
 * @returns VxeTableGridOptions 配置对象
 */
export function createBaseGridOptions<T = any>(
  pageQueryApi?: (query: PageQuery) => Promise<{ items: T[]; total: number }>,
): VxeTableGridOptions<T> {
  return {
    height: 'auto',
    keepSource: true,
    showOverflow: true,
    stripe: true,

    // 复选框配置
    checkboxConfig: {
      highlight: true,
      isShiftKey: true,
    },

    // 编辑配置
    editConfig: {
      trigger: 'click',
      mode: 'row',
      showStatus: true,
    },

    // 远程数据配置
    proxyConfig: {
      ajax: {
        query: async ({ page, sort, sorts }, formValues) => {
          if (!pageQueryApi) {
            return { items: [], total: 0 };
          }

          const query = buildPageQuery(page, sorts || sort, formValues);
          return await pageQueryApi(query);
        },
      },
      sort: true,
    },

    // 排序配置
    sortConfig: {
      remote: true,
      multiple: true,
    },

    // 工具栏配置
    toolbarConfig: {
      custom: true,
      search: true,
      export: true,
      refresh: { code: 'query' },
      zoom: true,
    },
    exportConfig: { type: 'csv', original: true },
  };
}

export function createBaseFormOptions(
  options: VbenFormProps = {},
): VbenFormProps {
  return {
    // 默认展开
    collapsed: false,
    // 时间字段映射配置
    fieldMappingTime: [],
    // 是否显示折叠按钮
    showCollapseButton: true,
    // 是否在字段值改变时提交表单
    submitOnChange: true,
    // 按下回车时是否提交表单
    submitOnEnter: false,
    // 默认的表单项配置
    schema: [],
    // 合并传入的配置
    ...options,
  };
}

/**
 * 创建布尔类型列配置
 * @param field 字段名
 * @param title 列标题
 * @returns 列配置对象
 */
export function createBooleanColumn(
  field: string,
  title: string,
  customConfig: Partial<Column<any>> = {},
  editable: boolean = true,
): Column<any> {
  const defaultConfig: any = {
    field,
    title,
    slots: { default: 'bool_render', edit: 'bool_edit' },
    width: 120,
    minWidth: 85,
    sortable: true,
  };

  if (editable) {
    defaultConfig.editRender = { name: 'input' };
  }

  return {
    ...defaultConfig,
    ...customConfig,
  };
}

/**
 * 创建枚举类型列配置
 * @param field 字段名
 * @param title 列标题
 * @param enumType 枚举类型
 * @param enumLabels 枚举标签映射
 * @returns 列配置对象
 */
export function createEnumColumn<EnumType extends number>(
  field: string,
  title: string,
  enumLabels: Record<EnumType, string>,
  customConfig: Partial<Column<any>> = {},
  editable: boolean = true,
): Column<any> {
  const defaultConfig: any = {
    field,
    title,
    width: 120,
    minWidth: 100,
    sortable: true,
    params: { enumLabels },
  };

  if (editable) {
    defaultConfig.editRender = {
      name: 'select',
      options: Object.entries(enumLabels).map(([value, label]) => ({
        value: Number(value) as EnumType,
        label,
      })),
    };
  }

  return {
    ...defaultConfig,
    ...customConfig,
  };
}
